// pages/index/letters_visits/add/add.js
import Toast from "../../../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../../../miniprogram_npm/@vant/weapp/dialog/dialog";

const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 4, //预约类型 （1.社保; 2.综; 3.视频探视预约; 4.信访预约(我帮你办事)）
    //具体预约类型
    orderTypeList: [],
    orderType: null,
    orderTypeShow: false,
    //预约日期
    date: null,
    dateShow: false,
    //预约时间
    currentTime: '9:00',
    time: null,
    timeShow: false,
    //手机号
    phone: null,
    //备注
    remark: null,
    //附件列表
    fileList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },


  /**
   * 手机号输入框
   * @param e
   */
  onPhoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  /**
   * 备注输入框
   * @param e
   */
  onInputRemark: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },

  /**
   * 关闭弹窗
   * @param e
   */
  onClose: function (e) {
    this.setData({
      orderTypeShow: false, //具体选择类型
      dateShow: false, //日期
      timeShow: false, //时间
    })
  },

  /**
   * 具体预约类型
   * @param e
   */
  onOrderType: function (e) {
    if (this.data.orderTypeList.length <= 0) {
      this.getOrderType()
    } else {
      this.setData({
        orderTypeShow: true
      })
    }
  },

  /**
   * 具体预约类型选择
   * @param e
   */
  onOrderTypeSelect: function (e) {
    this.setData({
      orderTypeShow: false,
      orderType: e.detail
    })
  },

  /**
   * 获取具体预约类型
   */
  getOrderType: function () {
    Toast.loading({
      duration: 0,
      message: "加载中..."
    })
    http.get(app.globalData.xw_system_url + "dic/getDicListByName/open",{
      name: "D0124"
    }).then(res => {
      if (res.data.code === http.REQUEST_OK) {
        Toast.clear()
        res.data.data.forEach(item => {
          item.name = item.dic_value
        })
        this.setData({
          orderTypeList: res.data.data,
          orderTypeShow: true
        })
      } else {
        Toast.fail(res.data.msg)
      }
    }, err => {
      Toast.fail("获取数据失败")
    })
  },


  /**
   * 日期选择
   * @param e
   */
  onDate: function (e) {
    this.setData({
      dateShow: true
    })
  },

  /**
   * 日期选择-确定
   * @param e
   */
  onDateConfirm: function (e) {
    const date = this.formatDate(e.detail)
    this.setData({
      date: date,
      dateShow: false
    })
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${(date.getMonth() + 1)<10?'0'+(date.getMonth() + 1):(date.getMonth() + 1)}-${date.getDate()<10?'0'+date.getDate():date.getDate()}`;
  },

  /**
   * 时间选择
   * @param e
   */
  onTime: function (e) {
    this.setData({
      timeShow: true
    })
  },

  /**
   * 时间选择-确定
   * @param e
   */
  onTimeConfirm: function (e) {
    log.e(e.detail)
    this.setData({
      currentTime: e.detail,
      time: e.detail,
      timeShow: false
    })
  },

  /**
   * 快速获取手机号
   * @param e
   */
  getPhoneNumber: function (e) {
    let _this = this
    wx.login({
      success: function (r) {
        Toast.loading({
          duration: 0,
          message: "获取中..."
        })
        http.get("applet/user/wxDecryptPhone", {
          appid: app.globalData.appId,
          code: r.code,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        }).then(res => {
          if (res.data.code === http.REQUEST_OK) {
            Toast.clear()
            wx.setStorage({
              key: "phone",  // 存储的key值
              data: res.data.data.phoneNumber   // 需要存储的值
            })
            _this.setData({
              phone: res.data.data.phoneNumber
            })
          } else {
            Toast.fail(res.data.msg)
          }
        }, err => {
          Toast.fail("网络异常，请稍后再试")
        })
      }
    })
  },

  /**
   * 添加附件
   * @param e
   */
  onAddFile: function (e) {
    wx.chooseMessageFile({
      count: 10,
      type: "all",
      success: scs => {
        let list = scs.tempFiles
        list.forEach(item => {
          http.upFile(item.path,"reserve").then(res => {
            if (res.code === http.REQUEST_OK) {
              this.data.fileList.push({
                name: item.name,
                url: res.data.url,
                type: res.data.suffix,
                isUp: true,
                path: item.path,
                tempType: item.type
              })
            } else {
              this.data.fileList.push({
                name: item.name,
                url: item.path,
                isUp: false,
                desc: res.msg,
                path: item.path,
                tempType: item.type
              })
            }
            this.setData({
              fileList: this.data.fileList
            })
          }, err => {
            this.data.fileList.push({
              name: item.name,
              url: item.path,
              isUp: false,
              desc: "网络异常",
              path: item.path,
              tempType: item.type
            })
            this.setData({
              fileList: this.data.fileList
            })
          })
        })
      }
    })
  },

  /**
   * 删除附件
   * @param e
   */
  onFileDelete: function (e) {
    const index = e.currentTarget.dataset.index
    this.data.fileList.splice(index,1)
    this.setData({
      fileList: this.data.fileList
    })
  },

  /**
   * 打开文件
   * @param e
   */
  onFileOpen: function (e) {
    const index = e.currentTarget.dataset.index
    let file = this.data.fileList[index]
    if (file.tempType == "image") {
      wx.previewMedia({
        sources: [{ url: file.path,type: "image"}],
        success: res => {

        },
        fail: fail => {
          wx.showToast({
            title: "打开文件失败",
            icon: "error"
          })
        }
      })
    } else if (file.tempType == "video") {
      wx.previewMedia({
        sources: [{ url: file.path,type: "video"}],
        success: res => {

        },
        fail: fail => {
          wx.showToast({
            title: "打开文件失败",
            icon: "error"
          })
        }
      })
    } else {
      wx.openDocument({
        filePath: file.path,
        success: res => {

        },
        fail: fail => {
          wx.showToast({
            title: "打开文件失败",
            icon: "error"
          })
        }
      })
    }
  },

  /**
   * 提交按钮
   * @param e
   */
  onSubmit: function (e) {
    log.e(JSON.stringify(this.data.fileList))
    if (this.data.type == 4) {
      //是否为 信访预约
      if (this.data.orderType == null) {
        Toast.fail("请选择预约类型")
        return;
      }
    }
    if (this.data.date == null) {
      Toast.fail("请选择预约日期")
      return;
    }
    if (this.data.phone == null || this.data.phone.length <= 0) {
      Toast.fail("请输入手机号或快速获取手机号")
      return;
    }
    if (this.data.phone.length < 11) {
      Toast.fail("请输入正确的手机号")
      return;
    }
    Toast.loading({
      duration: 0,
      message: "正在提交..."
    })
    //组装附件
    let file = []
    if (this.data.fileList.length > 0) {
      this.data.fileList.forEach(item => {
        if (item.isUp) {
          file.push({
            file_name: item.name,
            file_type: item.type,
            file_url: item.url
          })
        }
      })
    }
    http.postJson(app.globalData.xw_api_url + "online/order/add",{
      type: this.data.type,
      applet_id: app.globalData.appId,
      area_code: app.globalData.areaCode,
      people_id: app.globalData.userInfo.people_id,
      applet_user_id: app.globalData.userInfo.applet_user_id,
      phone: this.data.phone,
      remark: this.data.remark,
      order_date: this.data.date,
      order_type: this.data.orderType == null ? null : this.data.orderType.flag,
      order_name: this.data.orderType == null ? null : this.data.orderType.dic_value,
      attachment_list: file
    }).then(res => {
      if (res.data.code === http.REQUEST_OK) {
        Toast.success("提交成功")
        wx.navigateBack()
      } else {
        Toast.clear()
        Dialog.alert({
          title: "提交失败",
          message: res.data.msg
        }).then(() => {  })
      }
    }, err => {
      Toast.clear()
      Dialog.alert({
        title: "提交失败",
        message: "网络异常，请稍后再试！"
      }).then(() => {  })
    })
  },

})